package heartbeat

import (
	"ones-objects/lib/mq"
	"ones-objects/config"
	"time"
	"sync"
	"strconv"
)

var dataServers = make(map[string]time.Time)
var mutex sync.Mutex

func ListenHeartbeat()  {
	conf := mq.RabbitConf{
		Dsn: config.GetString(config.RABBITMQ_DSN),
		Queue:config.GetString(config.RABBITMQ_QUEUE_OBJECT),
		Exchange:config.GetStringDef(config.RABBITMQ_EXCHANGE_OBJECT, config.STR_EMPTY),
	}
	mq := mq.New(conf)
	defer mq.Close()

	msgs := mq.Consume()
	go removeExpiredDataServer()
	for msg := range msgs {
		dataServer,err := strconv.Unquote(string(msg.Body))
		if err != nil {
			panic(err)
		}
		mutex.Lock()
		dataServers[dataServer] = time.Now()
		mutex.Unlock()
	}

}

func removeExpiredDataServer()  {
	for  {
		time.Sleep(time.Second * 5)
		mutex.Lock()
		for k,v := range dataServers{
			if v.Add(time.Second * 10).Before(time.Now()) {
				delete(dataServers, k)
			}
		}
		mutex.Unlock()
	}
}

func GetDataServers() []string {
	mutex.Lock()
	defer mutex.Unlock()
	ds := make([]string, 0)
	for k,_ := range dataServers{
		ds = append(ds, k)
	}
	return ds
}

